package com.appleyk.pool;

import com.appleyk.config.ThreadPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>线程工厂（配置类）</p>
 *
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @github https://github.com/kobeyk
 * @date created on 12:30 2020/12/22
 */
@Configuration
public class ThreadPoolFactory {

    @Autowired
    private ThreadPoolConfig poolConfig;

    private final AtomicInteger tCount = new AtomicInteger(0);

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setThreadNamePrefix("task-");
        taskExecutor.setRejectedExecutionHandler(poolConfig.getHandler());
        taskExecutor.setCorePoolSize(poolConfig.getCorePoolSize());
        taskExecutor.setQueueCapacity(poolConfig.getQueueCapacity());
        taskExecutor.setMaxPoolSize(poolConfig.getMaximumPoolSize());
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Bean
    public ScheduledThreadPoolExecutor scheduledThreadPoolExecutor() {
        // 定时线程池执行器用的是一个无界（实际上是Integer.MAX_VALUE）的延迟队列
        // 指定延迟时间（周期性）来执行任务
        // 因此，maximumPoolSize对它来说是没有意义的
        // 线程池中的线程从DelayQueue中获取ScheduleFutureTask，然后执行任务。
        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                // 注意，这里new线程的时候，一定不要忘了第一个参数，否则线程池不会处理任务
                return new Thread(r,"scheduled-task-"+tCount.incrementAndGet());
            }
        };
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(poolConfig.getCorePoolSize());
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setThreadFactory(threadFactory);
        executor.setKeepAliveTime(poolConfig.getKeepAliveTime(), TimeUnit.SECONDS);
        return executor;
    }


    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = "hello";
        System.out.println(s1.equalsIgnoreCase(s2));
    }


}
